package com.blackfish.common.task;


import org.tio.core.udp.UdpClient;
import org.tio.core.udp.UdpClientConf;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @author tanyaowu
 */
public class FindCliTask implements Runnable{
    /**
     * @param args
     * @author tanyaowu
     */
    public UdpClientConf udpClientConf = null;
    public UdpClient udpClient = null;
    public String serverip = "127.0.0.1";
    public String findcliip = "127.0.0. 1";
    public boolean config = false;

    public void getMask(){
        for(int i=1;i<32;i++) {
            int ip = 0xFFFFFFFF << (32 - i);
            String binaryStr = Integer.toBinaryString(ip);
            StringBuffer buffer = new StringBuffer();
            for(int j=0;j<4;j++) {
                int beginIndex = j*8;
                buffer.append(Integer.parseInt(binaryStr.substring(beginIndex, beginIndex+8), 2)).append(".");
            }
            System.out.println("net mask "+i+" ,submask:"+buffer.substring(0,buffer.length()-1));

        }
    }

    void getHostIp(){

        // TODO 获取子网掩码
        try {
            InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
            String hostAddress = address.getHostAddress();//192.168.0.121
            serverip = hostAddress;
            String[] ip_list = hostAddress.split(".");
            ip_list[3] = "255";
            findcliip = String.join(".",ip_list);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }


    public void Config(){
        getHostIp();
        UdpClientConf udpClientConf = new UdpClientConf(findcliip, 3000, 5000);
        UdpClient udpClient = new UdpClient(udpClientConf);
        udpClient.start();
        this.config = true;
    }


    @Override
    public void run() {
        if(!this.config){
            this.Config();
        }
        for(int i=0;i<60;i++){
            udpClient.send(("{\"server ip\":\""+ this.serverip +"\"}").getBytes());
        }

    }
}